<script setup>
import { ref, computed, onMounted } from 'vue'
import dashboardApi from '@/api/dashboard.js'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页设置
const currentPage = ref(1)
const pageSize = ref(8)

// 排序相关
const sortField = ref('total')
const sortDirection = ref(-1) // 1升序，-1降序

// 搜索
const searchText = ref('')

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    
    // 调用后端API获取省份数据
    const response = await dashboardApi.getProvinceNum()
    
    if (response.code === 200 && response.data) {
      // 转换数据格式以匹配前端表格
      tableData.value = response.data.map(item => ({
        province: item.province || '未知',
        total: item.total || 0,
        dnssec: item.dnssec || 0,
        dot: item.dot || 0,
        doh: item.doh || 0,
        scanDate: item.scanDate || ''
      }))
    } else {
      console.warn('获取省份数据失败:', response.message)
      tableData.value = []
    }
  } catch (error) {
    console.error('获取省份数据失败:', error)
    
    // 如果是401错误，不显示错误消息，让响应拦截器处理跳转
    if (error.code === 401) {
      console.log('Token过期，响应拦截器将处理跳转')
      return
    }
    
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 分页计算
const filteredData = computed(() => {
  let data = [...tableData.value]
  
  // 搜索过滤
  if (searchText.value) {
    data = data.filter(item => 
      item.province.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  // 排序
  data.sort((a, b) => {
    const aVal = a[sortField.value] || 0
    const bVal = b[sortField.value] || 0
    return sortDirection.value * (aVal - bVal)
  })
  
  return data
})

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

const totalItems = computed(() => filteredData.value.length)

// 排序处理
const handleSort = (field) => {
  if (sortField.value === field) {
    sortDirection.value *= -1
  } else {
    sortField.value = field
    sortDirection.value = -1
  }
}

// 获取排序图标
const getSortIcon = (field) => {
  if (sortField.value !== field) return '↕️'
  return sortDirection.value === 1 ? '↑' : '↓'
}

// 计算安全评分
const getSecurityScore = (item) => {
  if (!item.total || item.total === 0) return 0
  const dnssecRate = (item.dnssec / item.total) * 100
  const dotRate = (item.dot / item.total) * 100
  const dohRate = (item.doh / item.total) * 100
  
  // 加权计算安全评分
  const score = (dnssecRate * 0.5 + dotRate * 0.25 + dohRate * 0.25)
  return Math.round(score)
}

// 获取评分颜色
const getScoreColor = (score) => {
  if (score >= 80) return '#4ade80'
  if (score >= 60) return '#fbbf24'
  if (score >= 40) return '#fb923c'
  return '#ef4444'
}

// 计算百分比
const getPercentage = (value, total) => {
  if (!total || total === 0) return 0
  return Math.round((value / total) * 100)
}

// 获取进度条宽度
const getProgressWidth = (value, max) => {
  return Math.min((value / max) * 100, 100)
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage >= 80) return '#22c55e'
  if (percentage >= 60) return '#f59e0b'
  if (percentage >= 40) return '#ef4444'
  return '#6b7280'
}

// 导出CSV
const exportToCSV = () => {
  const headers = ['省份', '递归服务器数量', '支持DNSSEC数量', '支持DoT数量', '支持DoH数量']
  const csvContent = [
    headers.join(','),
    ...tableData.value.map(item =>
        `"${item.province}",${item.total},${item.dnssec},${item.dot},${item.doh}`
    )
  ].join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)

  link.setAttribute('href', url)
  link.setAttribute('download', `DNS安全数据_${new Date().toLocaleDateString()}.csv`)
  link.style.visibility = 'hidden'

  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="modern-table-container">
    <!-- 表格头部工具栏 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <div class="search-container">
          <div class="search-wrapper">
            <i class="search-icon">🔍</i>
            <input 
              v-model="searchText" 
              type="text" 
              placeholder="搜索省份..."
              class="search-input"
            />
          </div>
        </div>
      </div>
      <div class="toolbar-right">
        <button @click="exportToCSV" class="export-btn">
          <i class="export-icon">📊</i>
          <span>导出数据</span>
        </button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper" v-loading="loading">
      <table class="modern-table">
        <thead>
          <tr>
            <th @click="handleSort('province')" :class="{ active: sortField === 'province' }">
              <div class="th-content">
                <span>省份</span>
                <span v-if="sortField === 'province'" class="sort-indicator">
                  {{ getSortIcon('province') }}
                </span>
              </div>
            </th>
            <th @click="handleSort('total')" :class="{ active: sortField === 'total' }">
              <div class="th-content">
                <span>服务器总数</span>
                <span v-if="sortField === 'total'" class="sort-indicator">
                  {{ getSortIcon('total') }}
                </span>
              </div>
            </th>
            <th @click="handleSort('dnssec')" :class="{ active: sortField === 'dnssec' }">
              <div class="th-content">
                <span>支持DNSSEC</span>
                <span v-if="sortField === 'dnssec'" class="sort-indicator">
                  {{ getSortIcon('dnssec') }}
                </span>
              </div>
            </th>
            <th @click="handleSort('dot')" :class="{ active: sortField === 'dot' }">
              <div class="th-content">
                <span>支持DoT</span>
                <span v-if="sortField === 'dot'" class="sort-indicator">
                  {{ getSortIcon('dot') }}
                </span>
              </div>
            </th>
            <th @click="handleSort('doh')" :class="{ active: sortField === 'doh' }">
              <div class="th-content">
                <span>支持DoH</span>
                <span v-if="sortField === 'doh'" class="sort-indicator">
                  {{ getSortIcon('doh') }}
                </span>
              </div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in paginatedData" :key="index" class="table-row">
            <td class="province-cell">
              <div class="province-wrapper">
                <span class="province-name">{{ item.province }}</span>
                <span class="province-rank">#{{ index + 1 + (currentPage - 1) * pageSize }}</span>
              </div>
            </td>
            <td class="number-cell">
              <span class="number-value">{{ item.total.toLocaleString() }}</span>
            </td>
            <td class="number-cell">
              <span class="number-value">{{ item.dnssec.toLocaleString() }}</span>
            </td>
            <td class="number-cell">
              <span class="number-value">{{ item.dot.toLocaleString() }}</span>
            </td>
            <td class="number-cell">
              <span class="number-value">{{ item.doh.toLocaleString() }}</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页器 -->
    <div class="pagination-wrapper">
      <div class="pagination-info">
        <span>显示 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, totalItems) }} 条，共 {{ totalItems }} 条</span>
      </div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 8, 10, 20]"
        :small="false"
        :total="totalItems"
        layout="sizes, prev, pager, next, jumper"
        background
        class="modern-pagination"
      />
    </div>
  </div>
</template>

<style scoped>
.modern-table-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: transparent;
  padding: 0;
}

/* 工具栏样式 */
.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 5px;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-container {
  position: relative;
}

.search-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-icon {
  position: absolute;
  left: 12px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.5);
  z-index: 1;
}

.search-input {
  width: 250px;
  height: 40px;
  padding: 0 15px 0 35px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  color: white;
  font-size: 14px;
  transition: all 0.3s ease;
}

.search-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.search-input:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.4);
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.1);
}

.export-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: rgba(76, 201, 240, 0.2);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(76, 201, 240, 0.3);
  border-radius: 20px;
  color: #4cc9f0;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.export-btn:hover {
  background: rgba(76, 201, 240, 0.3);
  border-color: rgba(76, 201, 240, 0.5);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(76, 201, 240, 0.2);
}

/* 表格样式 */
.table-wrapper {
  flex: 1;
  overflow: auto;
  background: transparent;
  margin-bottom: 20px;
}

.modern-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.modern-table thead {
  background: transparent;
  position: sticky;
  top: 0;
  z-index: 10;
}

.modern-table th {
  padding: 18px 15px;
  text-align: left;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.modern-table th:hover {
  background: rgba(255, 255, 255, 0.15);
}

.modern-table th.active {
  background: rgba(76, 201, 240, 0.2);
  color: #4cc9f0;
}

.th-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  color: white;
  font-size: 13px;
}

.sort-indicator {
  margin-left: 8px;
  font-size: 12px;
  color: #4cc9f0;
}

.table-row {
  transition: all 0.3s ease;
  border: none;
}

.table-row:hover {
  background: rgba(255, 255, 255, 0.05);
}

.modern-table td {
  padding: 12px 15px;
  vertical-align: middle;
  border: none;
}

/* 省份单元格 */
.province-cell {
  min-width: 100px;
}

.province-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.province-name {
  font-weight: 600;
  color: white;
  font-size: 15px;
}

.province-rank {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  font-weight: 500;
}

/* 数字单元格 */
.number-cell {
  min-width: 120px;
}

.number-wrapper {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.number-value {
  font-weight: 600;
  color: white;
  font-size: 14px;
}

.progress-bar {
  width: 100%;
  height: 4px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  transition: width 0.8s ease-in-out;
  border-radius: 2px;
}

/* 分页器 */
.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px;
}

.pagination-info {
  color: rgba(255, 255, 255, 0.7);
  font-size: 13px;
}

:deep(.modern-pagination) {
  background: transparent;
}

:deep(.modern-pagination .el-pagination__total),
:deep(.modern-pagination .el-pagination__jump) {
  color: rgba(255, 255, 255, 0.7);
}

:deep(.modern-pagination .el-pager li),
:deep(.modern-pagination .btn-prev),
:deep(.modern-pagination .btn-next) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  margin: 0 2px;
  border-radius: 8px;
}

:deep(.modern-pagination .el-pager li:hover),
:deep(.modern-pagination .btn-prev:hover),
:deep(.modern-pagination .btn-next:hover) {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
}

:deep(.modern-pagination .el-pager li.is-active) {
  background: #4cc9f0;
  border-color: #4cc9f0;
  color: white;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-input {
    width: 200px;
  }
  
  .modern-table {
    font-size: 12px;
  }
  
  .modern-table th,
  .modern-table td {
    padding: 12px 10px;
  }
}

@media (max-width: 768px) {
  .table-toolbar {
    flex-direction: column;
    gap: 15px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .modern-table {
    font-size: 11px;
  }
  
  .pagination-wrapper {
    flex-direction: column;
    gap: 15px;
  }
}
</style>